import { authRequestClient, baseRequestClient, requestClient } from '#/api/request';

export namespace AuthApi {
  /** 登录接口参数 */
  export interface LoginParams {
    password?: string;
    username?: string;
  }

  /** 登录接口返回值 */
  export interface LoginResult {
    accessToken: string;
    firstLogin?: boolean;
    message?: string;
  }

  /** 修改密码接口参数 */
  export interface ChangePasswordParams {
    username: string;
    password: string;
    realName: string; // 使用realName字段传递新密码
    email: string;    // 使用email字段传递校验新密码
  }

  /** 修改密码接口返回值 */
  export interface ChangePasswordResult {
    success?: boolean;
    message?: string;
  }

  export interface RefreshTokenResult {
    data: string;
    status: number;
  }

  /** Token状态查询返回值 */
  export interface TokenStatusResult {
    valid: boolean;
    username: string;
    remainingTimeMs: number;
    remainingTimeText: string;
    needsRefresh: boolean;
    expirationTime: string;
    newToken?: string;
  }

  /** Token手动续期返回值 */
  export interface TokenRefreshResult {
    newToken: string;
    username: string;
    userId: string;
    expirationTime: string;
  }

  /** Token配置信息返回值 */
  export interface TokenConfigResult {
    expirationTime: number;
    refreshThreshold: number;
    expirationTimeText: string;
    refreshThresholdText: string;
  }
}

/**
 * 登录
 */
export async function loginApi(data: AuthApi.LoginParams) {
  return requestClient.post<AuthApi.LoginResult>('/auth/login', data);
}

/**
 * 修改密码
 */
export async function changePasswordApi(data: AuthApi.ChangePasswordParams) {
  return authRequestClient.post<AuthApi.ChangePasswordResult>('/auth/change-password', data);
}

/**
 * 刷新accessToken
 */
export async function refreshTokenApi() {
  return authRequestClient.post<AuthApi.RefreshTokenResult>('/auth/refresh', {
    withCredentials: true,
  });
}

/**
 * 退出登录
 */
export async function logoutApi() {
  return authRequestClient.post('/auth/logout', {
    withCredentials: true,
  });
}

/**
 * 获取用户权限码
 */
export async function getAccessCodesApi() {
  return requestClient.get<string[]>('/auth/codes');
}

/**
 * 查询Token状态
 */
export async function getTokenStatusApi() {
  return requestClient.get<AuthApi.TokenStatusResult>('/token/status');
}

/**
 * 手动续期Token
 */
export async function refreshTokenManuallyApi() {
  return requestClient.post<AuthApi.TokenRefreshResult>('/token/refresh');
}

/**
 * 获取Token配置信息
 */
export async function getTokenConfigApi() {
  return authRequestClient.get<AuthApi.TokenConfigResult>('/token/config');
}
